package com.zx.mobile.controller;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import com.zx.map.dao.model.Employee;
import com.zx.map.dao.model.StoreInfo;
import com.zx.map.service.AgentInfoService;
import com.zx.map.service.BankService;
import com.zx.map.service.BaseAcctInfoService;
import com.zx.map.service.EmployeeService;
import com.zx.map.service.HistoryPayCardInfoService;
import com.zx.map.service.MerchantInfoService;
import com.zx.map.service.MerchantOfflineConfigInfoService;
import com.zx.map.service.MessageSendLogService;
import com.zx.map.service.OrdLogService;
import com.zx.map.service.SessionInfoService;
import com.zx.map.service.ShareProfitLogService;
import com.zx.map.service.StoreInfoService;
import com.zx.map.service.TodoTaskService;
import com.zx.map.service.model.AgentInfoModel;
import com.zx.map.service.model.BaseAcctInfoModel;
import com.zx.map.service.model.HistoryPayCardInfoModel;
import com.zx.map.service.model.MerchantInfoDetailModel;
import com.zx.map.service.model.MerchantInfoModel;
import com.zx.map.service.model.MerchantInfoTodoTask;
import com.zx.map.service.model.MerchantOfflineConfigInfoModel;
import com.zx.map.service.model.OrdLogModel;
import com.zx.map.service.model.ShareProfitLogModel;
import com.zx.map.utils.CommonResponseUtils;
import com.zx.map.utils.SUConstants;
import com.zx.mobile.MobileCommonHelper;
import com.zx.mobile.PayRateHelper;
import com.zx.mobile.SessionHelper;
import com.zx.mobile.domain.AcctInfoRequest;
import com.zx.mobile.domain.AcctInfoResponse;
import com.zx.mobile.domain.AppRegisterNewRequest;
import com.zx.mobile.domain.AppRegisterNewResponse;
import com.zx.mobile.domain.BindcardNewRequest;
import com.zx.mobile.domain.BindcardNewResponse;
import com.zx.mobile.domain.HistoryPaycardInfoResponse;
import com.zx.mobile.domain.HistoryPaycardRequest;
import com.zx.mobile.domain.LoginDomain;
import com.zx.mobile.domain.LoginResponse;
import com.zx.mobile.domain.MobileUserDomain;
import com.zx.mobile.domain.QrInfoRequest;
import com.zx.mobile.domain.QrInfoResponse;
import com.zx.mobile.domain.SendVerifyCodeRequest;
import com.zx.mobile.domain.SendVerifyCodeResponse;
import com.zx.mobile.domain.ShareProfitRequest;
import com.zx.mobile.domain.ShareProfitResponse;
import com.zx.mobile.domain.SysUpdateRequest;
import com.zx.mobile.domain.SysUpdateResponse;
import com.zx.mobile.domain.interf.CardPayOrderRequest;
import com.zx.mobile.domain.interf.CardPayOrderResponse;
import com.zx.mobile.domain.shareregister.ShareRegisterRequest;
import com.zx.mobile.domain.shareregister.ShareRegisterResponse;
import com.zx.mobile.service.proxy.AcctInfoCommonProxy;
import com.zx.mobile.service.proxy.AppRegisterCommonNewProxy;
import com.zx.mobile.service.proxy.BindCardCommonNewProxy;
import com.zx.mobile.service.proxy.CardPayOrderCommonProxy;
import com.zx.mobile.service.proxy.HistoryPayCardProxy;
import com.zx.mobile.service.proxy.HistoryPaycardCommonProxy;
import com.zx.mobile.service.proxy.LoginCommonProxy;
import com.zx.mobile.service.proxy.MessageSendProxy;
import com.zx.mobile.service.proxy.QrInfoCommonProxy;
import com.zx.mobile.service.proxy.ShareProfitCommonProxy;
import com.zx.mobile.service.proxy.SysUpdateCommonProxy;
import com.zx.mobile.service.proxy.share.ShareRegisterCommonProxy;
import com.zx.mobile.utils.WebUtils;
import com.zx.platform.utils.DateUtils;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.utils.StrUtils;
import com.zx.scp.service.model.MessageResponse;
import com.zx.scp.utils.MatrixToImageWriter;
import com.zx.scp.utils.PropertyUtil;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 15-7-5 Time: 下午8:09 To
 * change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/mobile/index")
public class MobileInterfaceController {
	/**
	 * log
	 */
	private static Logger log = Logger.getLogger(MobileInterfaceController.class);
	@Autowired
	private MerchantOfflineConfigInfoService merchantOfflineConfigInfoService;
	@Autowired
	private BankService bankService;
	@Autowired
	private MerchantInfoService merchantInfoService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private AgentInfoService agentInfoService;
	@Autowired
	private OrdLogService ordLogService;
	@Autowired
	private SessionInfoService sessionInfoService;
	@Autowired
	private TodoTaskService todoTaskService;
	@Autowired
	private MessageSendLogService messageSendLogService;
	@Autowired
	private ShareProfitLogService shareProfitLogService;
	@Autowired
	private BaseAcctInfoService baseAcctInfoService;
	@Autowired
	private HistoryPayCardInfoService historyPayCardInfoService;
	@Autowired
	private StoreInfoService storeInfoService;

	@RequestMapping("/downloadQr")
	public void downloadQr(MerchantInfoModel merchantInfoModel, Model model, HttpServletRequest request,
			HttpServletResponse response) {

		try {

			MerchantInfoDetailModel merchant = WebUtils.queryCurrentLoginMerchantInfoDetailModel(request);
			MerchantOfflineConfigInfoModel temp = merchantOfflineConfigInfoService
					.getModelByKey(merchant.getMerchantId());
			if (null != temp && !Objects.isNull(temp.getOfflinePayUrl())) {
				OutputStream os = response.getOutputStream();// 取得输出流
				response.reset();// 清空输出流
				response.setHeader("Pragma", "No-cache");
				response.setHeader("Cache-Control", "no-cache");
				response.setDateHeader("Expires", 0);
				response.setContentType("image/jpeg");
				response.setHeader("Content-disposition",
						"attachment; filename=" + URLEncoder.encode(temp.getMerchantShortName() + ".jpg", "UTF-8"));// 设定输出文件头
				int width = 640; // 二维码图片宽度
				int height = 640; // 二维码图片高度
				String format = "jpg";// 二维码的图片格式
				Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
				hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码
				BitMatrix bitMatrix = new MultiFormatWriter().encode(temp.getOfflinePayUrl(), BarcodeFormat.QR_CODE,
						width, height, hints);
				// 生成二维码
				MatrixToImageWriter.writeToStream(bitMatrix, format, os);
				// 输出
				os.close();
			}
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
		}
	}
	
	@RequestMapping("/downloadQrURL")
	public void downloadQrURL(HttpServletRequest request, HttpServletResponse response) {

		try {
			OutputStream os = response.getOutputStream();// 取得输出流
			response.reset();// 清空输出流
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType("image/jpeg");
			// response.setHeader("Content-disposition", "attachment; filename="+
			// URLEncoder.encode(request.getParameter("url") + ".jpg", "UTF-8"));// 设定输出文件头
			int width = 640; // 二维码图片宽度
			int height = 640; // 二维码图片高度
			String format = "jpg";// 二维码的图片格式
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码
			BitMatrix bitMatrix = new MultiFormatWriter().encode(request.getParameter("url"), BarcodeFormat.QR_CODE,
					width, height, hints);
			// 生成二维码
			MatrixToImageWriter.writeToStream(bitMatrix, format, os);
			// 输出
			os.close();
		} catch (Exception e) {
			log.error("内部异常", e);
		}
	}

	/**
	 * 登陆页面
	 *
	 * @param jsonStr
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/loginVerify")
	@ResponseBody
	public LoginResponse loginVerify(String jsonStr, Model model, HttpServletRequest request) {
		LoginResponse loginResponse = new LoginResponse();
		log.info("登陆调用参数:" + jsonStr);
		try {
			// 1、 基础验证
			if (StringUtils.isNotBlank(jsonStr)) {
				// json信息转请求对象
				LoginDomain loginDomain = MobileCommonHelper.transFormJson(jsonStr, LoginDomain.class);
				if (StringUtils.isNotBlank(loginDomain.getLoginAccount())
						&& StringUtils.isNotBlank(loginDomain.getLoginPassword())) {
					// 2、验证用户名及密码

					Employee emp = employeeService.getEmployeeByUserId(loginDomain.getLoginAccount());
					List<MerchantInfoModel> merchantlist = new ArrayList<MerchantInfoModel>();
					if (emp != null
							&& emp.getPassword().equals(PmpUtils.encoderByMD5(loginDomain.getLoginPassword()))) {
						loginResponse.setEmployeeType(emp.getType());
						merchantlist.add(merchantInfoService.getModelByKey(emp.getMerchantid()));
					} else {
						merchantlist = LoginCommonProxy.getMerchantByLoginRequest(merchantInfoService, loginDomain);
					}
				
					if (null != merchantlist && merchantlist.size() == 1) {
						if (!MobileCommonHelper.APPUSERSTATUS_LOCK.equals(merchantlist.get(0).getStatus())) {
							MobileUserDomain user = getMobileUserInfoByMerchantId(merchantlist.get(0).getMerchantId());

							// MerchantOfflineConfigInfoModel merchantOfflineConfigInfoModel
							// =merchantOfflineConfigInfoService.getModelByKey(key)
							MerchantInfoDetailModel detailModel = user.getMerchantInfoDetailModel();
							String sessionId = PmpUtils.getUUID();
							user.setKeepKey(sessionId);
							// 记录sessionId信息
							log.info("login session " + sessionId);
							request.getSession().setAttribute(SessionHelper.MOBILEUSER, user);
							// 1、先将loginKey为当前用户的 全部删除
							LoginCommonProxy.dealSessionInfo(sessionId, user, sessionInfoService);
							loginResponse.setReturnCode("0000");
							loginResponse.setReturnMsg("成功");
							loginResponse.setSessionId(sessionId);
							loginResponse.setAppUserId(detailModel.getMerchantId());// 增加appuserid
							// 对于未实名认证用户设置默认用户名
							if (MobileCommonHelper.APPUSERSTATUS_WAIT.equals(detailModel.getStatus())
									|| MobileCommonHelper.APPUSERSTATUS_NOTREQUEST.equals(detailModel.getStatus())) {
								loginResponse.setAppUserName("宝数用户");
							} else {
								loginResponse.setAppUserName(detailModel.getMerchantName());
							}

							loginResponse.setUserStatus(detailModel.getStatus());
							// 增加返回终端信息
							loginResponse.setTerminalNo(null != detailModel.getTerminalInfo()
									? detailModel.getTerminalInfo().getTerminalNo()
									: "");
							// 增加注册日期 及T0额度
							loginResponse
									.setRegisterDate(DateUtils.dateToString(detailModel.getCreateDate(), "yyyy-MM-dd"));
							loginResponse.setEnchashLimit(
									null != detailModel.getT0Limit() ? detailModel.getT0Limit().toString()
											: Double.toString(PayRateHelper.ENCASHT0LIMIT));
							loginResponse.setIdentityNo(
									null != detailModel.getLegalIdentityno() ? detailModel.getLegalIdentityno() : "");
							if (!"18001703488".equals(loginDomain.getLoginAccount())) {
								loginResponse.setRemark("0");
							}
							// 登陆接口 中有个remark 如果为空 ios游戏就放开
							loginResponse.setRemark(PropertyUtil.getValue("iosUpdate"));
							// 0.35改成0.5 edit by wenjw 2016.10.10
							// loginResponse.setQrNotifyInfo("支付手续费：0.5%（支付宝0.6%）");
							// edit by wenjw 2016.10.28
							// System.out.println("支付手续费：0.5% ");
							loginResponse.setQrNotifyInfo("支付手续费：0.38% ");
							loginResponse.setNocardNotifyInfo("支付手续费：0.5%");
							
							loginResponse.setSettleRateTypeId(detailModel.getSettleRateType());
							loginResponse.setDepth(detailModel.getDepth());
							loginResponse.setParentApproved(detailModel.getParentApproved());
							loginResponse.setParentMerchantId(detailModel.getParentMerchantId());
							loginResponse.setParentImg(detailModel.getBussinessImg());
							loginResponse.setParentName(detailModel.getMerchantName());
							
							
							loginResponse.setBank(bankService.getBankById(detailModel.getBankId()));
							
							
							log.info("登陆成功:" + ToStringBuilder.reflectionToString(loginResponse));
						} else {
							log.error("用户已锁定");
							loginResponse.setReturnCode("0005");
							loginResponse.setReturnMsg("用户已锁定");
						}
					} else {
						log.error("用户名或密码错误");
						loginResponse.setReturnCode("0001");
						loginResponse.setReturnMsg("用户名或密码错误");
					}
				} else {
					log.error("用户名或密码错误");
					loginResponse.setReturnCode("0001");
					loginResponse.setReturnMsg("用户名或密码错误");
				}
			} else {
				log.error("非法访问接口");
				loginResponse.setReturnCode("0001");
				loginResponse.setReturnMsg("用户名或密码错误");
			}
		} catch (Exception e) {
			log.error("系统内部异常", e);
			loginResponse.setReturnCode("9999");
			loginResponse.setReturnMsg("系统内部异常");
		}
		log.info("登陆调用返回:" + ToStringBuilder.reflectionToString(loginResponse));
		return loginResponse;

	}

	/**
	 * 验证码发送接口
	 *
	 * @param jsonStr
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/sendVerifyCode")
	@ResponseBody
	public SendVerifyCodeResponse sendVerifyCode(String jsonStr, Model model, HttpServletRequest request) {
		SendVerifyCodeResponse sendVerifyCodeResponse = new SendVerifyCodeResponse();
		log.info("验证码发送调用参数:" + jsonStr);
		try {
			// 1、 基础验证
			if (StringUtils.isNotBlank(jsonStr)) {
				// //json信息转请求对象
				SendVerifyCodeRequest sendVerifyCodeRequest = MobileCommonHelper.transFormJson(jsonStr,
						SendVerifyCodeRequest.class);
				if (StringUtils.isNotBlank(sendVerifyCodeRequest.getTelephone())) {
					if (!merchantInfoService.checkMerchantExistByTelephone(sendVerifyCodeRequest.getTelephone())) {
						// 传递订单号及订单金额
						MessageResponse response = MessageSendProxy.getMessageResponse(
								MobileCommonHelper.MESSAGETYPE_REGISTER, sendVerifyCodeRequest.getTelephone());
						if (null != response && "0000".equals(response.getReturnCode())) {
							// 2、验证用户名及密码
							sendVerifyCodeResponse.setReturnCode("0000");
							sendVerifyCodeResponse.setReturnMsg("验证码发送成功");
						} else {
							// 2、验证用户名及密码
							sendVerifyCodeResponse.setReturnCode("9999");
							sendVerifyCodeResponse.setReturnMsg(response.getErrMsg());
						}
					} else {
						sendVerifyCodeResponse.setReturnCode("0004");
						sendVerifyCodeResponse.setReturnMsg("用户已存在请勿重复注册");
						return sendVerifyCodeResponse;
					}
				} else {
					sendVerifyCodeResponse.setReturnCode("0002");
					sendVerifyCodeResponse.setReturnMsg("手机号为空");
				}
			} else {
				log.info("输入参数不合法");
				sendVerifyCodeResponse.setReturnCode("0003");
				sendVerifyCodeResponse.setReturnMsg("输入参数不合法");
			}
		} catch (Exception e) {
			log.error("系统内部异常", e);
			sendVerifyCodeResponse.setReturnCode("9999");
			sendVerifyCodeResponse.setReturnMsg("系统内部异常");
		}
		log.info("验证码发送调用返回:" + ToStringBuilder.reflectionToString(sendVerifyCodeResponse));
		return sendVerifyCodeResponse;
	}

	/**
	 * 检查是否更新接口
	 *
	 * @param jsonStr
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/getSysRuntimeInfo")
	@ResponseBody
	public SysUpdateResponse getSysRuntimeInfo(String jsonStr, Model model, HttpServletRequest request) {
		SysUpdateResponse sysUpdateResponse = new SysUpdateResponse();
		log.info("检查是否更新调用参数:" + jsonStr);
		try {
			// 1、 基础验证
			if (StringUtils.isNotBlank(jsonStr)) {
				// //json信息转请求对象
				SysUpdateRequest sysUpdateRequest = MobileCommonHelper.transFormJson(jsonStr, SysUpdateRequest.class);
				String checkValidate = SysUpdateCommonProxy.checkSysUpdate(sysUpdateRequest);
				if (StringUtils.isBlank(checkValidate)) {
					log.info("检查是否更新接口参数检查完毕");
					sysUpdateResponse = SysUpdateCommonProxy.getSysUpdateResponse(sysUpdateRequest);
				} else {
					log.info("输入参数不合法");
					sysUpdateResponse.setReturnCode("0003");
					sysUpdateResponse.setReturnMsg(checkValidate);
				}
			} else {
				log.info("输入参数不合法");
				sysUpdateResponse.setReturnCode("0003");
				sysUpdateResponse.setReturnMsg("输入参数不合法");
			}
		} catch (Exception e) {
			log.error("系统内部异常", e);
			sysUpdateResponse.setReturnCode("9999");
			sysUpdateResponse.setReturnMsg("系统内部异常");
		}
		log.info("检查是否更新调用返回:" + ToStringBuilder.reflectionToString(sysUpdateResponse));
		return sysUpdateResponse;
	}

	/**
	 * 获取用户信息 并session保存
	 *
	 * @param merchantId
	 * @return
	 */
	private MobileUserDomain getMobileUserInfoByMerchantId(String merchantId) {
		MobileUserDomain user = new MobileUserDomain();
		MerchantInfoDetailModel detail = merchantInfoService.getMerchantDetail(merchantId);
		user.setMerchantInfoDetailModel(detail);
		return user;
	}

	/**
	 * 获取刷卡支付订单号接口
	 *
	 * @param jsonStr
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/getCardPayOrder")
	@ResponseBody
	public CardPayOrderResponse getCardPayOrder(String jsonStr, Model model, HttpServletRequest request) {
		CardPayOrderResponse cardPayOrderResponse = new CardPayOrderResponse();
		log.info("获取刷卡支付订单号调用参数:" + jsonStr);
		try {
			// 1、 基础验证
			if (StringUtils.isNotBlank(jsonStr)) {
				// //json信息转请求对象
				CardPayOrderRequest cardPayOrderRequest = MobileCommonHelper.transFormJson(jsonStr,
						CardPayOrderRequest.class);
				String checkValidate = CardPayOrderCommonProxy.checkCardPay(cardPayOrderRequest);
				if (StringUtils.isBlank(checkValidate)) {
					log.info("获取刷卡支付订单参数检查完毕");
					MerchantInfoModel temp = merchantInfoService.getModelByKey(cardPayOrderRequest.getAppUserId());
					if (null != temp) {
						OrdLogModel ordLogModel = CardPayOrderCommonProxy.getCardPayOrdLogModel(cardPayOrderRequest,
								temp);
						ordLogService.add(ordLogModel);
						cardPayOrderResponse = CardPayOrderCommonProxy.getCardPayResponse(ordLogModel.getOrdId());
					} else {
						log.info("用户不存在，请检查");
						cardPayOrderResponse.setReturnCode("0003");
						cardPayOrderResponse.setReturnMsg("用户不存在");
					}
				} else {
					log.info("输入参数不合法");
					cardPayOrderResponse.setReturnCode("0003");
					cardPayOrderResponse.setReturnMsg(checkValidate);
				}
			} else {
				log.info("输入参数不合法");
				cardPayOrderResponse.setReturnCode("0003");
				cardPayOrderResponse.setReturnMsg("输入参数不合法");
			}
		} catch (Exception e) {
			log.error("系统内部异常", e);
			cardPayOrderResponse.setReturnCode("9999");
			cardPayOrderResponse.setReturnMsg("系统内部异常");
		}
		log.info("获取刷卡支付订单号调用返回:" + ToStringBuilder.reflectionToString(cardPayOrderResponse));
		return cardPayOrderResponse;
	}

	/**
	 * app注册接口new
	 *
	 * @param jsonStr
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/appRegisterNew")
	@ResponseBody
	public AppRegisterNewResponse appRegisterNew(String jsonStr, Model model, HttpServletRequest request) {
		AppRegisterNewResponse appRegisterNewResponse = new AppRegisterNewResponse();
		log.info("注册接口调用参数:" + jsonStr);
		try {
			// 1、 基础验证
			if (StringUtils.isNotBlank(jsonStr)) {
				// json信息转请求对象
				AppRegisterNewRequest appRegisterNewRequest = MobileCommonHelper.transFormJson(jsonStr,
						AppRegisterNewRequest.class);
				String checkValidate = AppRegisterCommonNewProxy.checkAppRegister(appRegisterNewRequest,
						messageSendLogService);
				if (StringUtils.isBlank(checkValidate)) {
					log.info("验证合法保存用户信息");
					// 检查是否存在重复用户
					if (!merchantInfoService.checkMerchantExistByTelephone(appRegisterNewRequest.getTelephone())) {
						MerchantInfoModel merchantModel = AppRegisterCommonNewProxy
								.transFormRequest(appRegisterNewRequest);
						if (StringUtils.isNotBlank(appRegisterNewRequest.getInvitationCode())) {
							AgentInfoModel temp = agentInfoService
									.getAgentInfoModelBySysAccount(appRegisterNewRequest.getInvitationCode());
							if (null != temp) {
								merchantModel.setAgentId(temp.getAgentId());//
								merchantModel.setAgentSysAccount(appRegisterNewRequest.getInvitationCode());
							} else {
								appRegisterNewResponse.setReturnCode("0003");
								appRegisterNewResponse.setReturnMsg("邀请码输入有误");
								return appRegisterNewResponse;
							}
						} else {
							merchantModel.setAgentId(SUConstants.DEFAULT_SUBAGENTID);// TODO
						}
						String appUserId = merchantInfoService.add(merchantModel);
						// 2、验证用户名及密码
						log.info("app注册成功");
						appRegisterNewResponse.setReturnCode("0000");
						appRegisterNewResponse.setReturnMsg("app注册成功");
						appRegisterNewResponse.setAppUserId(appUserId);
						return appRegisterNewResponse;
					} else {
						appRegisterNewResponse.setReturnCode("0004");
						appRegisterNewResponse.setReturnMsg("用户已存在请勿重复注册");
						return appRegisterNewResponse;
					}
				} else {
					log.info("验证不合法");
					appRegisterNewResponse.setReturnCode("0002");
					appRegisterNewResponse.setReturnMsg(checkValidate);
				}
			} else {
				log.info("输入参数不合法");
				appRegisterNewResponse.setReturnCode("0003");
				appRegisterNewResponse.setReturnMsg("输入参数不合法");
			}
		} catch (Exception e) {
			log.error("系统内部异常", e);
			appRegisterNewResponse.setReturnCode("9999");
			appRegisterNewResponse.setReturnMsg("系统内部异常");
		}
		log.info("注册接口调用返回:" + ToStringBuilder.reflectionToString(appRegisterNewResponse));
		return appRegisterNewResponse;
	}

	/**
	 * 用户绑卡接口new
	 *
	 * @param jsonStr
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/bindcardNew")
	@ResponseBody
	@Transactional
	public Map bindcardNew(@RequestBody StoreInfo storeInfo, Model model, HttpServletRequest request) {
//		BindcardNewResponse bindcardNewResponse = new BindcardNewResponse();
//		log.info("用户绑卡调用参数:" + jsonStr);
		
		try {
			Objects.requireNonNull(storeInfo);
			MerchantInfoDetailModel merchant = WebUtils.queryCurrentLoginMerchantInfoDetailModel(request);
			String merchantId = merchant.getMerchantId();
			storeInfo.setMerchantId(merchantId);
			// 1、 基础验证
			if (!Objects.isNull(storeInfo)) {
				// json信息转请求对象
//				StoreInfo storeInfo = MobileCommonHelper.transFormJson(jsonStr,
//						StoreInfo.class);
				String checkValidate = BindCardCommonNewProxy.checkStoreInfo(storeInfo);
				if (StringUtils.isBlank(checkValidate)) {
					log.info("验证合法保存绑卡待审核事项");
					// 检查是否存在重复用户或者是审核拒绝的用户
					
					if (!merchantInfoService.checkMerchantByIdentityNo(storeInfo.getIdentifyNo()) || merchantInfoService.checkStoreInfoByMerchantId(storeInfo.getMerchantId())) {
						MerchantInfoModel merchantModel = merchantInfoService.getModelByKey(storeInfo.getMerchantId());
						if (null != merchantModel) {
							//认证信息
							StoreInfo store = storeInfoService.find(storeInfo.getMerchantId());
							if(Objects.nonNull(store)) {
								storeInfo.setStoreId(store.getStoreId());
								storeInfo.setTodoTaskId(store.getTodoTaskId());
							}
							MerchantInfoTodoTask todoTask = BindCardCommonNewProxy.addBindCardRequest(storeInfo, merchantModel, request);
							merchantModel.setUpdateDate(new Date());
							merchantModel.setLegalIdentityno(storeInfo.getIdentifyNo());
							merchantModel.setLegalName(storeInfo.getRealName());
							merchantModel.setMerchantName(storeInfo.getStoreName());
							merchantModel.setT0Limit(PayRateHelper.ENCASHT0LIMIT);// 增加T0额度内容
							merchantModel.setStatus(MobileCommonHelper.APPUSERSTATUS_WAIT);// 待审核状态
							merchantInfoService.update(merchantModel);// 更新字段内容
							
							// 设置TODOtask 发起申请人 用户均为代理发起新增 申请人设置为代理编号
							todoTask.getTodoTaskModel().setApplyOperator(merchantModel.getAgentSysAccount());
							todoTask.setMerchantInfoModel(merchantModel);
							// 直接把todoTask序列化
							
							if(Objects.isNull(store)) {

								Integer taskId = todoTaskService.addTodoTask(todoTask, todoTask.getTodoTaskModel());
								storeInfo.setTodoTaskId(taskId);
								storeInfoService.add(storeInfo);//插入门店信息
							}else {
								Integer taskId = todoTaskService.updateTodoTask(todoTask, todoTask.getTodoTaskModel());
								storeInfo.setTodoTaskId(taskId);
								storeInfoService.update(storeInfo);//更新门店信息
							}
							
							log.info("用户绑卡申请成功");
							// 2、returnmsg
//							bindcardNewResponse.setReturnCode("0000");
//							bindcardNewResponse.setReturnMsg("用户绑卡成功");
//							bindcardNewResponse.setUserStatus(MobileCommonHelper.APPUSERSTATUS_WAIT); // 待审核状态
							return CommonResponseUtils.successResponse();
							
						} else {
							log.info("绑卡用户不存在");
//							bindcardNewResponse.setReturnCode("0003");
//							bindcardNewResponse.setReturnMsg("绑卡用户不存在");
							return CommonResponseUtils.failureResponse("绑卡用户不存在!");
						}
					} else {
//						bindcardNewResponse.setReturnCode("0004");
//						bindcardNewResponse.setReturnMsg("身份证已注册请勿重复注册");
						return CommonResponseUtils.failureResponse("身份证已注册请勿重复注册!");
					}
				} else {
					log.info("验证不合法：" + checkValidate);
//					bindcardNewResponse.setReturnCode("0002");
//					bindcardNewResponse.setReturnMsg(checkValidate);
					return CommonResponseUtils.failureResponse(checkValidate);
				}
			} else {
				log.info("输入参数不合法");
//				bindcardNewResponse.setReturnCode("0003");
//				bindcardNewResponse.setReturnMsg("输入参数不合法");
				return CommonResponseUtils.failureResponse("输入参数不合法!");
			}
		}catch (Exception e) {
			log.error("系统内部异常", e);
//			bindcardNewResponse.setReturnCode("9999");
//			bindcardNewResponse.setReturnMsg("系统内部异常");
			return CommonResponseUtils.failureResponse("系统内部异常!");
		}
//		log.info("用户绑卡调用返回:" + ToStringBuilder.reflectionToString(bindcardNewResponse));
//		return bindcardNewResponse;
	}

	/**
	 * 二维码信息获取接口
	 *
	 * @param jsonStr
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/getQrInfoByUserId")
	@ResponseBody
	public QrInfoResponse getQrInfoByUserId(String jsonStr, Model model, HttpServletRequest request) {
		QrInfoResponse qrInfoResponse = new QrInfoResponse();
		log.info("二维码信息调用参数:" + jsonStr);
		try {
			// 1、 基础验证
			if (StringUtils.isNotBlank(jsonStr)) {
				// //json信息转请求对象
				QrInfoRequest qrInfoRequest = MobileCommonHelper.transFormJson(jsonStr, QrInfoRequest.class);
				String checkValidate = QrInfoCommonProxy.checkQrInfo(qrInfoRequest);
				if (StringUtils.isBlank(checkValidate)) {
					log.info("二维码信息获取参数检查完毕");
					qrInfoResponse = QrInfoCommonProxy.getQrInfoResponse(qrInfoRequest);
				} else {
					log.info("输入参数不合法");
					qrInfoResponse.setReturnCode("0003");
					qrInfoResponse.setReturnMsg(checkValidate);
				}
			} else {
				log.info("输入参数不合法");
				qrInfoResponse.setReturnCode("0003");
				qrInfoResponse.setReturnMsg("输入参数不合法");
			}
		} catch (Exception e) {
			log.error("系统内部异常", e);
			qrInfoResponse.setReturnCode("9999");
			qrInfoResponse.setReturnMsg("系统内部异常");
		}
		log.info("二维码信息调用返回:" + ToStringBuilder.reflectionToString(qrInfoResponse));
		return qrInfoResponse;
	}

	/**
	 * 分享注册
	 *
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/visit")
	public String visit(String key, Model model, HttpServletRequest request) {
		try {
			model.addAttribute("key", key);
			return "/jsp/mobile/visit/index";
		} catch (Exception e) {
			model.addAttribute("errorMsg", "访问出错了");
			log.error("访问出错了", e);
			return "/jsp/mobile/error";
		}
	}

	/**
	 * 分享注册
	 *
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/preregister")
	public String preregister(String key, Model model, HttpServletRequest request) {
		try {
			log.info("key:" + key);
			sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
			String merchantId = new String(decoder.decodeBuffer(key));
			MerchantInfoModel temp = merchantInfoService.getModelByKey(merchantId);
			if (null != temp) {
				model.addAttribute("model", temp);
				return "/jsp/mobile/visit/register";
			} else {
				model.addAttribute("errorMsg", "访问出错了");
				return "/jsp/mobile/error";
			}
		} catch (Exception e) {
			model.addAttribute("errorMsg", "访问出错了");
			log.error("访问出错了", e);
			return "/jsp/mobile/error";
		}
	}

	/**
	 * 通过分享注册 邀请码建议 分步处理 提高注册成功率
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/registerByShare")
	@ResponseBody
	public ShareRegisterResponse registerByShare(ShareRegisterRequest shareRegisterRequest, Model model,
			HttpServletRequest request) {
		ShareRegisterResponse shareRegisterResponse = new ShareRegisterResponse();
		log.info("分享注册调用参数:" + ToStringBuilder.reflectionToString(shareRegisterRequest));
		try {
			// 1、 基础验证
			String checkValidate = ShareRegisterCommonProxy.checkShareRegister(shareRegisterRequest,
					messageSendLogService);
			if (StringUtils.isBlank(checkValidate)) {
				log.info("分享注册验证合法保存用户信息");
				// 检查是否存在重复用户
				if (!merchantInfoService.checkMerchantExistByTelephone(shareRegisterRequest.getTelephone())) {
					MerchantInfoModel merchantModel = ShareRegisterCommonProxy.transFormRequest(shareRegisterRequest);
					if (StringUtils.isNotBlank(shareRegisterRequest.getInvitationCode())) {
						AgentInfoModel temp = agentInfoService
								.getAgentInfoModelBySysAccount(shareRegisterRequest.getInvitationCode());
						if (null != temp) {// 对于分享的用户 如果不是代理自动升级为代理
							merchantModel.setAgentId(temp.getAgentId());
						} else {
							// 未转换为代理的 根据商户信息自动提升了代理
							MerchantInfoModel merModel = merchantInfoService
									.getMerchantInfoModelBySysAccount(shareRegisterRequest.getInvitationCode());
							AgentInfoModel param = new AgentInfoModel();
							param.setSysAccount(merModel.getSysAccount());
							param.setRemark("分享升级");
							if (merModel.getMerchantName() == null) {
								param.setAgentName(merModel.getSysAccount());
							} else {
								param.setAgentName(merModel.getMerchantName());
							}
							param.setContacts(merModel.getMerchantName());
							param.setAgentLevel(SUConstants.AGENT_LEVEL_WILL);// 代理类型 普通类型
							param.setAgentType("1");
							param.setSysPassword(SUConstants.DEFAULT_PWD);
							// 对于新增代理 需要维护上下级归属关系 parentagentid bsid
							// 查询上级信息
							AgentInfoModel parentAgent = agentInfoService.getModelByKey(merModel.getAgentId());
							// 构造保存信息
							agentInfoService.saveAgentInfo(param, parentAgent);
							String agentId = param.getAgentId();
							if (StrUtils.isBlank(agentId)) {
								shareRegisterResponse.setReturnCode("9999");
								shareRegisterResponse.setReturnMsg("系统内部异常");
								return shareRegisterResponse;
							}
							merchantModel.setAgentId(agentId);
						}
						merchantModel.setAgentSysAccount(shareRegisterRequest.getInvitationCode());
					} else {
						merchantModel.setAgentId(SUConstants.DEFAULT_SUBAGENTID);// TODO
					}
					String appUserId = merchantInfoService.add(merchantModel);
					// 2、验证用户名及密码
					log.info("app注册成功");
					shareRegisterResponse.setReturnCode("0000");
					shareRegisterResponse.setReturnMsg("app注册成功");
					shareRegisterResponse.setAppUserId(appUserId);
					return shareRegisterResponse;
				} else {
					shareRegisterResponse.setReturnCode("0004");
					shareRegisterResponse.setReturnMsg("用户已存在请勿重复注册");
					return shareRegisterResponse;
				}
			} else {
				log.info("验证不合法");
				shareRegisterResponse.setReturnCode("0002");
				shareRegisterResponse.setReturnMsg(checkValidate);
			}
		} catch (Exception e) {
			log.error("系统内部异常", e);
			shareRegisterResponse.setReturnCode("9999");
			shareRegisterResponse.setReturnMsg("系统内部异常");
		}
		log.info("分享注册调用返回:" + ToStringBuilder.reflectionToString(shareRegisterResponse));
		return shareRegisterResponse;
	}

	/**
	 * 分享收益
	 *
	 * @param jsonStr
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/getShareProfitByUserId")
	@ResponseBody
	public ShareProfitResponse getShareProfitByUserId(String jsonStr, Model model, HttpServletRequest request) {
		ShareProfitResponse shareProfitResponse = new ShareProfitResponse();
		log.info("分享收益调用参数:" + jsonStr);
		try {
			// 1、 基础验证
			if (StringUtils.isNotBlank(jsonStr)) {
				// //json信息转请求对象
				ShareProfitRequest shareProfitRequest = MobileCommonHelper.transFormJson(jsonStr,
						ShareProfitRequest.class);
				String merchantId = shareProfitRequest.getAppUserId();
				MerchantInfoModel merchantInfoModel = merchantInfoService.getModelByKey(merchantId);
				String checkValidate = ShareProfitCommonProxy.checkShareProfit(shareProfitRequest);
				if (StringUtils.isBlank(checkValidate)) {
					log.info("分享收益参数检查完毕");
					DecimalFormat df = new DecimalFormat("0.00");
					shareProfitResponse = ShareProfitCommonProxy.getShareProfitResponse(shareProfitRequest);
					ShareProfitLogModel profit = shareProfitLogService
							.queryProfitByCustSysAccount(merchantInfoModel.getSysAccount());
					shareProfitResponse.setProfit(null != profit ? df.format(profit.getSprofitAvlAmt()) : "0.00");
				} else {
					log.info("输入参数不合法");
					shareProfitResponse.setReturnCode("0003");
					shareProfitResponse.setReturnMsg(checkValidate);
				}
			} else {
				log.info("输入参数不合法");
				shareProfitResponse.setReturnCode("0003");
				shareProfitResponse.setReturnMsg("输入参数不合法");
			}
		} catch (Exception e) {
			log.error("系统内部异常", e);
			shareProfitResponse.setReturnCode("9999");
			shareProfitResponse.setReturnMsg("系统内部异常");
		}
		log.info("分享收益调用返回:" + ToStringBuilder.reflectionToString(shareProfitResponse));
		return shareProfitResponse;
	}

	/**
	 * 账户信息
	 *
	 * @param jsonStr
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/getAcctInfoByUserId")
	@ResponseBody
	public AcctInfoResponse getAcctInfoByUserId(String jsonStr, Model model, HttpServletRequest request) {
		AcctInfoResponse acctInfoResponse = new AcctInfoResponse();
		log.info("账户信息调用参数:" + jsonStr);
		try {
			// 1、 基础验证
			if (StringUtils.isNotBlank(jsonStr)) {
				// //json信息转请求对象
				AcctInfoRequest acctInfoRequest = MobileCommonHelper.transFormJson(jsonStr, AcctInfoRequest.class);
				String checkValidate = AcctInfoCommonProxy.checkAcctInfo(acctInfoRequest);
				if (StringUtils.isBlank(checkValidate)) {
					log.info("账户信息参数检查完毕");
					acctInfoResponse = AcctInfoCommonProxy.getShareProfitResponse(acctInfoRequest);
					// 获取账户信息
					String merchantId = acctInfoRequest.getAppUserId();
					MerchantInfoModel merchantInfoModel = merchantInfoService.getModelByKey(merchantId);
					DecimalFormat df = new DecimalFormat("0.00");
					BaseAcctInfoModel baseAcctInfoModel = baseAcctInfoService
							.getModelByKey(acctInfoRequest.getAppUserId());
					acctInfoResponse
							.setAcctAmt(null != baseAcctInfoModel ? df.format(baseAcctInfoModel.getAvlBal()) : "0.00");
					// 获取分享收益
					ShareProfitLogModel profit = shareProfitLogService
							.queryProfitByCustSysAccount(merchantInfoModel.getSysAccount());
					acctInfoResponse.setProfit(null != profit ? df.format(profit.getSprofitAvlAmt()) : "0.00");
				} else {
					log.info("输入参数不合法");
					acctInfoResponse.setReturnCode("0003");
					acctInfoResponse.setReturnMsg(checkValidate);
				}
			} else {
				log.info("输入参数不合法");
				acctInfoResponse.setReturnCode("0003");
				acctInfoResponse.setReturnMsg("输入参数不合法");
			}
		} catch (Exception e) {
			log.error("系统内部异常", e);
			acctInfoResponse.setReturnCode("9999");
			acctInfoResponse.setReturnMsg("系统内部异常");
		}
		log.info("账户信息调用返回:" + ToStringBuilder.reflectionToString(acctInfoResponse));
		return acctInfoResponse;
	}

	/**
	 * 获取账户历史收款账号
	 *
	 * @param jsonStr
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/getHistoryPaycardByUserId")
	@ResponseBody
	public HistoryPaycardInfoResponse getHistoryPaycardByUserId(String jsonStr, Model model,
			HttpServletRequest request) {
		HistoryPaycardInfoResponse historyPaycardInfoResponse = new HistoryPaycardInfoResponse();
		log.info("历史收款账号信息调用参数:" + jsonStr);
		try {
			// 1、 基础验证
			if (StringUtils.isNotBlank(jsonStr)) {
				// //json信息转请求对象
				HistoryPaycardRequest historyPaycardRequest = MobileCommonHelper.transFormJson(jsonStr,
						HistoryPaycardRequest.class);
				String checkValidate = HistoryPaycardCommonProxy.checkHistoryPaycardInfo(historyPaycardRequest);
				if (StringUtils.isBlank(checkValidate)) {
					log.info("历史收款账号信息参数检查完毕");
					historyPaycardInfoResponse = HistoryPaycardCommonProxy
							.getHistoryPaycardResponse(historyPaycardRequest);
					// 获取历史收款账号信息
					HistoryPayCardInfoModel param = new HistoryPayCardInfoModel();
					param.setMerchantId(historyPaycardRequest.getAppUserId());
					List<HistoryPayCardInfoModel> list = historyPayCardInfoService.getListByModel(param);
					list = HistoryPayCardProxy.transformHistoryPayCardForApp(list);
					historyPaycardInfoResponse.setHistoryPayCardInfoModelList(list);
				} else {
					log.info("输入参数不合法");
					historyPaycardInfoResponse.setReturnCode("0003");
					historyPaycardInfoResponse.setReturnMsg(checkValidate);
				}
			} else {
				log.info("输入参数不合法");
				historyPaycardInfoResponse.setReturnCode("0003");
				historyPaycardInfoResponse.setReturnMsg("输入参数不合法");
			}
		} catch (Exception e) {
			log.error("系统内部异常", e);
			historyPaycardInfoResponse.setReturnCode("9999");
			historyPaycardInfoResponse.setReturnMsg("系统内部异常");
		}
		log.info("历史收款账号信息调用返回:" + ToStringBuilder.reflectionToString(historyPaycardInfoResponse));
		return historyPaycardInfoResponse;
	}
}
